<?php
namespace App\Http\Controllers\Api\Vocabulary;

use App\Enums\Api\Response;
use App\Http\Controllers\Controller;
use App\Models\Category\Category;
use App\Models\Category\CategoryModule;
use App\Models\Data\ClickLearn;
use App\Models\Tool\FileUrl;
use App\Models\Vocabulary\VocabularyOption;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Models\Vocabulary\Vocabulary;
use Illuminate\Support\Str;
class VocabularyController extends Controller
{
    public function list(Request $request):JsonResponse
    {
        $unitList=Category::query()->select('id','name','unit_main_name')
                ->where('parent_id', $request->input('gradeId'))
            ->has('vocabulary.click_learn')->get()->toArray();
        return apiResponse(code:Response::SERVICE_SUCCESS->value,data:array_map(function ($v){
            return [
                'id'=>$v['id'],
                'name'=>$v['name'],
                'unit'=>$v['unit_main_name'],
            ];
        },$unitList),msg: Response::SERVICE_SUCCESS->response(),type: 'vocabulary');
    }
    public function follow(int $categoryId):JsonResponse
    {
        if (!Vocabulary::query()->with('click_learn')->where(['category_id'=>$categoryId,'type'=>Vocabulary::TYPE_READ_AFTER])->exists()){
            return apiResponse(code:Response::SYSTEM_DATA_NOT_EXISTS->value,data:[],msg: Response::SYSTEM_DATA_NOT_EXISTS->response(),type: 'vocabulary_follow');
        }
        $gradeId=Category::query()->where('id',$categoryId)->value('parent_id');
        $vocabularyList=Vocabulary::query()->with('click_learn')->where(['category_id'=>$categoryId,'type'=>Vocabulary::TYPE_READ_AFTER])->get();
        $file_url=FileUrl::query()->where('module',CategoryModule::ModuleTypeTwo)->first();
        $result = [];
        $currentGroup = [];
        $lastOnSort = null;
        $newVocabularyList=[];
        foreach($vocabularyList as $v){
            if ($v['on_sort'] == 0) {
                if (!empty($currentGroup)) {
                    $result[] = $currentGroup;
                    $currentGroup = [];
                }
                $result[] = [$v['id']];
                $lastOnSort = $v['on_sort'];
            }
            if ($lastOnSort == 1 ||  $v['on_sort'] == 1) {
                $currentGroup[] = $v['id'];
                $lastOnSort =  $v['on_sort'];
            }
            $newVocabularyList[]=[
                'id'=>$v['id'],
                'click_id'=>$v['click_learn']['id'],
                'content'=>$v['click_learn']['content'],
                'translation'=>$v['click_learn']['translation'],
                'audio_url'=>convert_file_address_exist(module:CategoryModule::ModuleTypeTwo,file_address:$v['click_learn']['audio_url']??'',grade:$gradeId,category:$categoryId,type: '.mp3',file_url: $file_url),
                'image_url'=>convert_file_address_exist(module:CategoryModule::ModuleTypeTwo,file_address:$v['click_learn']['image_url']??'',grade:$gradeId,category:$categoryId,type: '.png',file_url: $file_url),
                'spell_url'=>convert_file_address_exist(module:CategoryModule::ModuleTypeTwo,file_address:$v['click_learn']['spell_audio']??'',grade:$gradeId,category:$categoryId,type: '.mp3',file_url: $file_url),
                'phonetic'=>$v['click_learn']['phonetic'],
                'type'=>$this->type_convert($v['click_learn']['type'])
            ];
        }
        return apiResponse(code:Response::SERVICE_SUCCESS->value,data:['data'=>$newVocabularyList,'sort_data'=>$result],msg: Response::SERVICE_SUCCESS->response(),type: 'virtual_page');

    }
    public function spell(int $categoryId):JsonResponse
    {
        if (!Vocabulary::query()->with('click_learn')->where(['category_id'=>$categoryId,'type'=>Vocabulary::TYPE_AUDITION_LOOK_SPELL_WORD])->exists()){
            return apiResponse(code:Response::SYSTEM_DATA_NOT_EXISTS->value,data:[],msg: Response::SYSTEM_DATA_NOT_EXISTS->response(),type: 'vocabulary_spell');
        }
        $gradeId=Category::query()->where('id',$categoryId)->value('parent_id');
        $file_url=FileUrl::query()->where('module',CategoryModule::ModuleTypeTwo)->first();
        $spellList= Vocabulary::query()
            ->with(['click_learn.spell_options','click_learn.spells:id,click_learn_id,name,time,color'])
            ->where(['category_id'=>$categoryId,'type'=>Vocabulary::TYPE_AUDITION_LOOK_SPELL_WORD])->get()->toArray();
        $result = [];
        $currentGroup = [];
        $lastOnSort = null;
        $newVocabularyList=[];
        foreach ($spellList as $spell) {
            if ($spell['on_sort'] == 0) {
                if (!empty($currentGroup)) {
                    $result[] = $currentGroup;
                    $currentGroup = [];
                }
                $result[] = [$spell['id']];
                $lastOnSort = $spell['on_sort'];
            }
            if ($lastOnSort == 1 || $spell['on_sort'] == 1) {
                $currentGroup[] = $spell['id'];
                $lastOnSort = $spell['on_sort'];
            }
            $newVocabularyList[] = [
                'id' => $spell['id'],
                'click_id' => $spell['click_learn']['id'],
                'title' => $spell['click_learn']['content'],
                'phonetic' => $spell['click_learn']['phonetic'],
                'translation' => $spell['click_learn']['translation'],
                'url'=>convert_file_address_exist(module:CategoryModule::ModuleTypeTwo,file_address:$spell['click_learn']['audio_url']??'',grade:$gradeId,category:$categoryId,type: '.mp3',file_url: $file_url),
                'word_blanks' => $spell['click_learn']['word_blanks'],
                'option' => isset($spell['click_learn']['option']) ? explode('|', $spell['click_learn']['option']) : [],
                'option_order' => isset($spell['click_learn']['option_order']) ? explode('|', $spell['click_learn']['option_order']) : [],
                'spell_url'=>convert_file_address_exist(module:CategoryModule::ModuleTypeTwo,file_address:$spell['click_learn']['spell_audio']??'',grade:$gradeId,category:$categoryId,type: '.mp3',file_url: $file_url),
                'spells' => $spell['click_learn']['spells'] ?? [],
                'spell_options' => $spell['click_learn']['spell_options'] ?? [],
            ];
        }
        return apiResponse(code:Response::SERVICE_SUCCESS->value,data:['data'=>$newVocabularyList,'sort_data'=>$result],msg: Response::SERVICE_SUCCESS->response(),type: 'virtual_spell');
    }
    public function exercise(int $categoryId):JsonResponse
    {
        if (!Vocabulary::query()->with('click_learn')->where(['category_id'=>$categoryId])->whereIn('type',
            [Vocabulary::TYPE_SELECT_WORD_BLANKS,Vocabulary::TYPE_AUDITION_WORD,Vocabulary::TYPE_IMAGE_LISTEN_PRACTICE,Vocabulary::TYPE_CHINESE_SELECT_ENGLISH])->exists()){
            return apiResponse(code:Response::SYSTEM_DATA_NOT_EXISTS->value,data:[],msg: Response::SYSTEM_DATA_NOT_EXISTS->response(),type: 'vocabulary_spell');
        }
        $gradeId=Category::query()->where('id',$categoryId)->value('parent_id');
        $file_url=FileUrl::query()->where('module',CategoryModule::ModuleTypeTwo)->first();
        $jsonData=Vocabulary::query()->with(['click_learn','item'])
            ->where(['category_id'=>$categoryId])->whereIn('type',
                [Vocabulary::TYPE_SELECT_WORD_BLANKS,Vocabulary::TYPE_AUDITION_WORD,Vocabulary::TYPE_IMAGE_LISTEN_PRACTICE,Vocabulary::TYPE_CHINESE_SELECT_ENGLISH])->get()->toArray();
        $result = [];
        $currentGroup = [];
        $lastOnSort = null;
        $newVocabularyList=[];
        foreach($jsonData as $cate) {
            if (!empty($cate['click_learn'])) {
                if ($cate['on_sort'] == 0) {
                    if (!empty($currentGroup)) {
                        $result[] = $currentGroup;
                        $currentGroup = [];
                    }
                    $result[] = [$cate['id']];
                    $lastOnSort = $cate['on_sort'];
                }
                if ($lastOnSort == 1 || $cate['on_sort'] == 1) {
                    $currentGroup[] = $cate['id'];
                    $lastOnSort = $cate['on_sort'];
                }

                if ($cate['type']==Vocabulary::TYPE_SELECT_WORD_BLANKS){
                    $audio_url=$cate['item']['audio_url']??'';
                }else{
                    $audio_url=$cate['click_learn']['audio_url']??'';
                }
                if ($cate['type']==Vocabulary::TYPE_SELECT_WORD_BLANKS){
                    $image_url=$cate['item']['image_url']??'';
                }else{
                    $image_url=$cate['click_learn']['image_url']??'';
                }
                if ($cate['type']==Vocabulary::TYPE_SELECT_WORD_BLANKS){
                    $spell_audio=$cate['item']['spell_audio']??'';
                }else{
                    $spell_audio=$cate['click_learn']['spell_audio']??'';
                }
                if ($cate['type']==Vocabulary::TYPE_IMAGE_LISTEN_PRACTICE){
                    $audio_url=$cate['item']['audio_url']??'';
                    $image_url=$cate['item']['image_url']??'';
                }
                $newVocabularyList[]= [
                    'id'=>$cate['id'],
                    'sentence'=>Str::replace('{0}', '______', $cate['sentence']),
                    'type'=>$cate['type'],
                    'sentence_answer'=>$cate['item']['content']??'',
                    'sentence_translation'=>$cate['item']['translation']??'',
                    'url'=>convert_file_address_exist(module:CategoryModule::ModuleTypeTwo,file_address:$audio_url,grade:$gradeId,category:$categoryId,type: '.mp3',file_url: $file_url),
                    'image_url'=>convert_file_address_exist(module:CategoryModule::ModuleTypeTwo,file_address:$image_url,grade:$gradeId,category:$categoryId,type: '.png',file_url: $file_url),
                    'spell_audio'=>convert_file_address_exist(module:CategoryModule::ModuleTypeTwo,file_address:$spell_audio,grade:$gradeId,category:$categoryId,type: '.mp3',file_url: $file_url),
                    'title'=>$cate['click_learn']['translation']??'',
                    'content'=>$cate['click_learn']['content']??'',
                    'answer_id'=>$cate['click_learn']['id']??'',
                    'options'=>VocabularyOption::query()->where('vocabulary_id',$cate['id'])->get()->pluck('title')
                ]  ;
            }
        }
        return apiResponse(code:Response::SERVICE_SUCCESS->value,data:['data'=>$newVocabularyList,'sort_data'=>$result],msg: Response::SERVICE_SUCCESS->response(),type: 'virtual_spell');
    }
    protected function type_convert(int $type): string
    {
        return match ($type) {
            ClickLearn::TYPE_SENTENCE => 'sentence',
            default => 'word',
        };
    }
}
